#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<signal.h>
#include<unistd.h>
#include<sys/wait.h>

void signalDeal(int signum){
    wait(NULL);
}
int main(){
    signal(SIGCHLD, signalDeal);
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd < 0){
        perror("socket");
        return 0;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(22222);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    int ret = bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0){
        perror("bind");
        return 0;
    }
    ret = listen(listen_fd, 5);
    if(ret < 0){
        perror("listen");
        return 0;
    }

    //收发消息
    while(1){
        struct sockaddr_in cli_addr;
        socklen_t cli_addr_len = sizeof(cli_addr);
        int new_sockfd = accept(listen_fd, (struct sockaddr*)&cli_addr,&cli_addr_len);
        if(new_sockfd < 0){
            perror("accept");
            return 0;
        }
        pid_t pid = fork();
        if(pid < 0){
            close(new_sockfd);
            continue;
        }else if(pid == 0){
            //子进程负责与客户端沟通
            close(listen_fd);
            while(1){
                char buf[1024] = {0};
                int recv_size = recv(new_sockfd, buf, sizeof(buf) - 1, 0);
                if(recv_size < 0){
                    perror("recv");
                    continue;
                }else if(recv_size == 0){
                    //客户端将连接关闭
                    printf("perr shutdown!\n");
                    close(new_sockfd);
                    return 0;
                }
                printf("[%s]:[%d] say [%s]\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), buf);
                memset(buf, '\0', sizeof(buf));
                sprintf(buf, "I am server, I recv your msg");
                send(new_sockfd, buf, strlen(buf), 0);
            }
        }else{
            close(new_sockfd);
        }
    }
    return 0;
}
